<?php

use \Mapper\AdminModel as AdminMapper;

class AdminController extends \Base\AbstractController {

//    protected $layout = '';
//
//    public function init() {
//        parent::init();
//        $this->disableLayout();
//    }

    public function loginAction() {
        //关闭模板布局
        $this->disableLayout();
        $request  = $this->getRequest();
        $username = (string)trim($request->get('username'));
        $password = (string)trim($request->get('password'));

        if($request->isPost()) {

            if(empty($username)) {
                return \Response::errmsg('Empty username.');
            }

            if(empty($password)) {
                return \Response::errmsg('Empty password.');
            }

            $mapper = AdminMapper::getInstance();
            $model  = $mapper->fetch(['username' => $username, 'status' => 1]);

            if(!$model instanceof \AdminModel || \Lib\Passwd::valid($password, $model->getPassword()) === false) {
                return \Response::errmsg('Error username or password.');
            }

            $loginIp = \Lib\Tool::getClientIp(false);
            $loginIp = empty($loginIp) ? 0 : $loginIp;
            $model->setLast_login_ip($loginIp);
            $model->setLast_login_time(time());

            try {
                $rows = $mapper->update($model, ['id' => $model->getId()]);

                if($rows > 0) {
                    $this->getSession()->set('Admin', ['id' => $model->getId(), 'ip' => $loginIp]);

                    return \Response::msg('Login success.', '/admin/');
                } else {
                    return \Response::errmsg('Logon failed.');
                }
            } catch(\Exception $e) {
                return \Response::errmsg($e->getMessage());
            }
        }

    }

    public function logoutAction() {
        $this->getSession()->del('Admin');
        $this->redirect('/admin/admin/login');
    }

    public function listAction() {
        $page = new \Lib\Paginator('admin');
        $this->assign('page', $page->getPage());
        $this->assign('perPage', $page->getPerpage());
        $this->assign('count', $page->count());
        $this->assign('lists',$page->lists());
    }

    public function addAction() {
        $adminMapper = \Mapper\AdminModel::getInstance();
        $model = new AdminModel();
        $model->setAdd_time(time());
        $model->setStatus(1);
        $model->setNickname('BOSS');
        $model->setPassword(\Lib\Passwd::encrypt('123456'));
        $model->setUsername('chenyu');

        try{
            $adminMapper->insert($model);
            echo 'success!';
        }catch (Exception $exc){
            echo $exc->getMessage();
        }
    }

}
